package com.qf.medicaldoctoradmin.onlineSigning.TeamHomepage.task;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qf.common.entity.Doctor;
import com.qf.medicaldoctoradmin.onlineSigning.TeamHomepage.dao.DoctorDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * redis中的对应医生签约的人数同步到数据库中
 */


@Component
public class RedisToDatabaseSyncTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DoctorDao doctorDao; // 假设这是一个数据库操作接口



    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨0点执行
    public void syncDoctorSignupsToDatabase() {
        // 获取所有医生的签约人数
        Set<String> doctorKeys = redisTemplate.keys("doctor:*:signups");
        for (String key : doctorKeys) {
            // 获取医生的签约人数
            Integer signupCount = (Integer) redisTemplate.opsForValue().get(key);
            // 更新数据库中的签约人数
            String[] split = key.split(":");
            // 医生id
            int doctorId = Integer.parseInt(split[1]);
            Doctor doctor = new Doctor();
            doctorDao.update(doctor,new LambdaUpdateWrapper<Doctor>()
                    .eq(Doctor::getId, doctorId)// 指定 ID 为 doctorId
                    .set(Doctor::getSignNum, signupCount));
        }
    }
}
